#!/bin/bash
# ====================================================
# Pre-commit hook: Auto detect Gradle / Gradle Wrapper
# Supports skipping hook and configuration
# ====================================================


# Default values
PREFER_GLOBAL_GRADLE=${PREFER_GLOBAL_GRADLE:-true}
SKIP_HOOK_ENV_VAR=${SKIP_HOOK_ENV_VAR:-SKIP_HOOK}

# 1️⃣ 跳过 hook
if [ "${!SKIP_HOOK_ENV_VAR}" == "1" ]; then
    echo "$SKIP_HOOK_ENV_VAR=1 detected. Skipping pre-commit check..."
    exit 0
fi

# 2️⃣ 自动选择 Gradle 命令
if [ "$PREFER_GLOBAL_GRADLE" == "true" ] && command -v gradle >/dev/null 2>&1; then
    GRADLE_CMD="gradle"
elif [ -f "./gradlew" ]; then
    GRADLE_CMD="./gradlew"
elif [ -f "./gradlew.bat" ]; then
    GRADLE_CMD="./gradlew.bat"
else
    echo "No Gradle or Gradle Wrapper found! commit aborted."
    exit 1
fi

# 3️⃣ 执行检查
echo "Running '$GRADLE_CMD check' before commit..."
$GRADLE_CMD check
RESULT=$?

if [ $RESULT -ne 0 ]; then
    echo "Gradle check failed. commit aborted."
    echo "To skip this check, run: $SKIP_HOOK_ENV_VAR=1 git commit"
    exit 1
fi

echo "Gradle check passed. Proceeding with commit..."
exit 0
